<?php

namespace app\api\model;

use think\facade\Db;
use app\api\validate\Faceprint as FaceprintValidate;
use think\exception\ValidateException;

class Faceprint
{
    /**
     * 获取实名认证跳转地址
     */
    public function getAuthUrl($params)
    {
        try {
            validate(FaceprintValidate::class)->check($params);
        } catch (ValidateException $e) {
            return fail($e->getError());
        }

        try {
            $ai = new \baidu\Ai;
        } catch (ValidateException $e) {
            return fail($e->getError());
        }

        $verifyToken = $ai->getVerifyToken();
        if (false === $verifyToken) {
            return fail($ai->getError());
        }

        $queryNo = $this->generateQueryNo();
        if (false === $queryNo) {
            return fail('系统繁忙，请稍后重试。');
        }

        $id = Db::name('baidu_ai_verify_log')
            ->insertGetId([
                'verify_token' => $verifyToken,
                'operator_id' => $params['operator_id'],
                'query_no' => $queryNo,
                'notify_url' => $params['notify_url'] ?? '',
                'result' => '[]',
            ]);
        if (!$id) {
            return fail('系统繁忙，请稍后重试');
        }

        // 激动的时刻即将到来，终于可以请出认证 URL
        $domain = request()->domain();
        $successUrl = urlencode($domain . '/api/baidu/success?q=' . $queryNo);
        $failedUrl = urlencode($domain . '/api/baidu/failed?q=' . $queryNo);
        $url = 'https://brain.baidu.com/face/print/?token=' . $verifyToken . '&successUrl=' . $successUrl . '&failedUrl=' . $failedUrl;

        return success('提交成功', [
            'url' => $url,
            'query_no' => $queryNo,
        ]);
    }

    /**
     * 获取实名认证跳转地址
     */
    public function getAuthUrlOld($params)
    {
        try {
            validate(FaceprintValidate::class)->check($params);
        } catch (ValidateException $e) {
            return fail($e->getError());
        }

        $params['id_no'] = strtoupper($params['id_no']);
        if ($params['certificate_type'] == 0) {
            if (false === checkIdCard($params['id_no'])) {
                return fail('身份证号码格式有误');
            }
        }

        try {
            $ai = new \baidu\Ai;
        } catch (ValidateException $e) {
            return fail($e->getError());
        }

        $verifyToken = $ai->getVerifyToken();
        if (false === $verifyToken) {
            return fail($ai->getError());
        }

        $queryNo = $this->generateQueryNo();
        if (false === $queryNo) {
            return fail('系统繁忙，请稍后重试。');
        }

        $id = Db::name('baidu_ai_verify_log')
            ->insertGetId([
                'verify_token' => $verifyToken,
                'id_name' => $params['id_name'],
                'id_no' => $params['id_no'],
                'certificate_type' => $params['certificate_type'],
                'query_no' => $queryNo,
                'result' => '[]',
            ]);
        if (!$id) {
            return fail('系统繁忙，请稍后重试');
        }

        $params['verify_token'] = $verifyToken;
        $res = $ai->idcardSubmit($params);
        if (empty($res['success'])) {
            return fail('百度用户信息上报失败：' . json_encode($res, JSON_UNESCAPED_UNICODE));
        }

        // 激动的时刻即将到来，终于可以请出认证 URL
        $domain = request()->domain();
        $successUrl = urlencode($domain . '/api/baidu/success?q=' . $queryNo);
        $failedUrl = urlencode($domain . '/api/baidu/failed?q=' . $queryNo);
        $url = 'https://brain.baidu.com/face/print/?token=' . $verifyToken . '&successUrl=' . $successUrl . '&failedUrl=' . $failedUrl;

        return success('提交成功', [
            'url' => $url,
        ]);
    }

    private function generateQueryNo()
    {
        for ($i = 0; $i < 211; $i++) {
            $queryNo = date('ymdHis') . str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
            $id = Db::name('baidu_ai_verify_log')
                ->where('query_no', $queryNo)
                ->value('id');
            if (empty($id)) {
                return $queryNo;
            }
        }
        return false;
    }

    /**
     * 查询结果
     */
    public function query($queryNo)
    {
        $info = Db::name('baidu_ai_verify_log')
            ->where('query_no', $queryNo)
            ->find();
        if (empty($info)) {
            return fail('记录未找到');
        }
        $result = json_decode($info['result'], true);
        if (!empty($result)) {
            $result['operator_id'] = $info['operator_id'];
            return success('查询成功', $result);
        }

        $ai = new \baidu\Ai;
        $result = $ai->resultDetail($info['verify_token']);
        Db::name('baidu_ai_verify_log')
            ->where('id', $info['id'])
            ->update([
                'result' => json_encode($result, JSON_UNESCAPED_UNICODE),
            ]);
        $result['operator_id'] = $info['operator_id'];
        return success('查询成功', $result);
    }
}